package com.jxtc.enterprise.common.utils;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;

/**
 * 统一API响应结果封装
 *
 * @param <T> 返回 data 数据的范型
 */
@Schema(title = "统一API响应结果封装")
@Getter
public class Result<T> {
    @Schema(title = "响应码")
    private int code;

    @Schema(title = "响应信息")
    private String message;

    @Schema(title = "响应数据")
    private T data;

    public Result<T> setCode(int code) {
        this.code = code;
        return this;
    }

    /**
     * 仅包含通过 ResultCode 设置的 code 字段的方式，会导致 JSON 转换成 Result 对象时 setCode 方法失效，故增加 setCode(int code) 方法
     */
    public Result<T> setCode(ResultCode resultCode) {
        this.code = resultCode.code();
        return this;
    }

    public Result<T> setMessage(String message) {
        this.message = message;
        return this;
    }

    public Result<T> setData(T data) {
        this.data = data;
        return this;
    }

    public Result() {
    }

    public Result(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public static Result<?> ok() {
        return new Result<String>(200, "success", null);
    }

    public static Result<?> ok(String msg) {
        return new Result<String>(200, "success", msg);
    }

    public static Result<?> error(String errMsg) {
        return new Result<String>(500, "failed", errMsg);
    }

    @Override
    public String toString() {
        return "Result{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }
}
